﻿using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Snowflake.Net;
using SqlSugar;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XinLife.Core.Extention;

namespace XinLife.Application
{
    public static class DbSetup
    {
        public static void AddSugarDB(this WebApplicationBuilder builder)
        {
            builder.Services.AddScoped<ISqlSugarClient>(s =>
            {
                SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.MySql,
                    ConnectionString = builder.Configuration.GetConnectionString("BaseDb"),
                    IsAutoCloseConnection = true,
                    ConfigureExternalServices = new ConfigureExternalServices()
                    {
                        EntityService = (property, column) =>
                        {
                            var attributes = property.GetCustomAttributes(true);//get all attributes 

                            if (attributes.Any(it => it is KeyAttribute))// by attribute set primarykey
                            {
                                column.IsPrimarykey = true; //有哪些特性可以看 1.2 特性明细
                            }
                            if (attributes.Any(it => it is NotMappedAttribute))
                            {
                                column.IsIgnore = true;
                            }
                        },
                        EntityNameService = (type, entity) =>
                        {
                            var attributes = type.GetCustomAttributes(true);
                            if (attributes.Any(it => it is TableAttribute))
                            {
                                entity.DbTableName = (attributes.First(it => it is TableAttribute) as TableAttribute).Name;
                            }
                        }
                    }
                },
               db =>
               {
                   //单例参数配置，所有上下文生效
                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                       //获取IOC对象不要求在一个上下文
                       //vra log=s.GetService<Log>()

                       //获取IOC对象要求在一个上下文
                       //var appServive = s.GetService<IHttpContextAccessor>();
                       //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
                   };
                   db.Aop.DataExecuting = (oldValue, entityInfo) =>
                   {
                       if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(string) && entityInfo.EntityValue.GetPropertyValue(entityInfo.EntityColumnInfo.DbColumnName) == null)
                       {
                           entityInfo.SetValue(Guid.NewGuid().ToString("N"));
                       }
                       else if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long) && entityInfo.EntityValue.GetPropertyValue(entityInfo.EntityColumnInfo.DbColumnName) == null)
                       {
                           entityInfo.SetValue(IdWorkerHelper.GenId64());
                       }
                   };
               });
                return sqlSugar;
            });
        }
    }
}
